import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { useMappedState, useDispatch } from 'redux-react-hook';
import {
  Row, Col, Input, Button, Form, message
} from 'antd';
import {
  LockOutlined, UserOutlined, EyeTwoTone, EyeInvisibleOutlined, PictureOutlined
} from '@ant-design/icons';

import { checkImgCode } from '@@/utils/validators';
import { PublicState } from '@@/store/reducers';
import {
  ac_uuid_async,
  ac_login
} from '@@/store/actions';

import style from "./Login.module.less";

const Login = () => {
  /* --=====================状态定义=====================-- */
  const [ imgCodeUrl, setImgCodeUrl ] = useState('');
  const imgCode = useMappedState((state: PublicState) => state.imgCode);
  const login = useMappedState((state: PublicState) => state.login)
  const history = useHistory();
  const dispatch = useDispatch();

  /* --=====================副作用=====================-- */
  // 获取图片验证码
  useEffect(() => {
    dispatch(ac_uuid_async());
  }, [dispatch])

  // 处理验证码图片base64编码
  useEffect(() => {
    if (imgCode && imgCode.data.byteLength > 0) {
      const base64str: string = btoa(String.fromCharCode(...new Uint8Array(imgCode.data)));
      const base64Url: string = `data:image/png;base64,${base64str}`;
      setImgCodeUrl(base64Url);
    }
  }, [imgCode])

  useEffect(() => {
    if (login.res) {
      if (login.res.retCode === '0') {
        message.success('登录成功');
        localStorage.setItem('sessionKey', login.res.message);
        history.replace('/');
      } 
    }
  })

  /* --=====================固定状态定义=====================-- */
  // 表单 label 定位
  const layout = {
    labelCol: { span: 0 }
  }

  // 校验文本对象
  /* eslint-disable no-template-curly-in-string */
  const validateMessage = {
    required: '请输入${label}'
  }
  /* eslint-disable no-template-curly-in-string */

  /* --=====================事件处理=====================-- */
  // 处理表单提交事件
  const handleFormFinish = (formData: any) => {
    const param = {
      ...formData,
      uuid: imgCode.uuid
    };
    dispatch(ac_login(param, dispatch));
  }

  // 处理图片验证码点击事件
  const handleImgCodeClick = () => {
    dispatch(ac_uuid_async());
  }

  return (
    <div className={style.login}>
      <div className="login_box">
        <div className="logo"></div>
        <div className="sysmsg">德会项目办公助手管理系统</div>
        <div className="input_box">
          <div className="welcome">
            <span>欢迎登录</span>
          </div>
          <Form validateMessages={validateMessage} validateTrigger="onBlur" onFinish={handleFormFinish}>
            <Form.Item {...layout}  label="用户名" rules={[{ required: true }]} name="userName">
              <Row className="login_row">
                <Col span={24}>
                  <Input size="large" placeholder="请输入账号" prefix={<LockOutlined />}></Input>
                </Col>
              </Row>
            </Form.Item>
            <Form.Item {...layout}  label="密码" rules={[{ required: true }]} name="passWord">
              <Row className="login_row">
                <Col span={24}>
                  <Input.Password
                    size="large"
                    placeholder="请输入密码"
                    prefix={<UserOutlined />}
                    iconRender={(visiable: boolean) => visiable ? <EyeTwoTone /> : <EyeInvisibleOutlined />}
                  />
                </Col>
              </Row>
            </Form.Item>
            <Form.Item {...layout}  label="验证码" rules={[{ validator: checkImgCode }]} name="userCaptcha">
              <Row className="login_row">
                <Col span={16}>
                  <Input maxLength={4} size="large" className="imgCode_input" prefix={<PictureOutlined />} placeholder="请输入图片验证码"></Input>
                </Col>
                <Col span={8}>
                  <img className="imgCode_img" alt="图片验证码" src={imgCodeUrl} onClick={handleImgCodeClick}/>
                </Col>
              </Row>
            </Form.Item>
            <Form.Item>
              <div className="login_btn">
                <Button loading={login.loginLoading} type="primary" htmlType="submit">登录</Button>
              </div>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  )
}

export default Login;